package com.pms.api;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pms.cache.utils.RedisCacheUtil;
import com.pms.controller.BaseController;
import com.pms.entity.EstateDoorCard;
import com.pms.entity.EstateDoorLock;
import com.pms.entity.OpenDoorRecord;
import com.pms.service.IEstateDoorLockService;
import com.pms.service.IOpenDoorRecordService;
import com.pms.util.DaHaoLockUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@Api(value = "大豪设备的回调接口", description = "大豪设备的回调接口")
@RequestMapping(value = "dahaoCallBack", method = RequestMethod.POST)
public class DaHaoCallBackApi extends BaseController {
    @Autowired
    private DaHaoLockUtil daHaoLockUtil;
    @Autowired
    private IEstateDoorLockService estateDoorLockService;

    @SuppressWarnings({"unchecked", "unused"})
    @ApiOperation(value = "大豪设备的回调接口")
    @RequestMapping(value = "/read/callBackParse")
    public Object callBackParse(HttpServletRequest request, ModelMap modelMap, String PARAMS) {
        JSONObject resultJson = null;
        resultJson = JSONObject.fromObject(PARAMS);
        String OPERATE = resultJson.getString("OPERATE");
        if (OPERATE.equals("1B")) {//gprs开门
            logger.info("gprs开门回调 ========================");
            logger.info(resultJson.toString());
//            try {
//                if (resultJson.getInt("RESULT") == 0) {//开门成功
//                    daHaoLockUtil.addOpenDoorRecord( resultJson.getString("DEVICEID"), new Date());
//                }
//            } catch (Exception ex) {
//                ex.printStackTrace();
//            }
            daHaoLockUtil.saveOpenDoorNumBySqlFunction(resultJson.getString("DEVICEID"));
        }
        if (OPERATE.equals("40")) {//开锁记录自动上传回调   类型   2-密码开门3-刷卡开门
//    			["F369FB8C","1","3","6F26AC6400000000","1","2000-01-01 00:31:43"]
//    			设备ID ：记录条数：类型：卡片id：操作方式(1->开锁) ：操作时间
            logger.info("开锁记录自动上传回调 ========================");
            logger.info(resultJson.toString());
            daHaoLockUtil.saveOpenDoorNumBySqlFunction(resultJson.getString("DEVICEID"));
        }
        if (OPERATE.equals("27")) {//发卡  直接发卡回调
            logger.info("gprs发卡回调 ========================");
            logger.info(resultJson.toString());
//    		String PARAMS_str = resultJson.getString("PARAMS");
//		    JSONArray PARAMS_Array = JSONArray.fromObject(PARAMS_str);
//		    String DEVICE_ID = PARAMS_Array.get(0).toString();//设备Id
//			String result_code = PARAMS_Array.get(1).toString();
//			//获取请求时间
//			Long requestTime = (Long)redisCacheUtil.getVlue("estateLockCard:sendFiveHundredCardRequestTime:"+DEVICE_ID.trim());
//			long responseTime = System.currentTimeMillis();//获取响应时间
//			long disTime = (responseTime-requestTime)/1000;
//			if (disTime>15) {//如果发卡操作时间超过10秒，设置状态超时
//				//重新发卡
//				daHaoLockUtil.sendTenCard(DEVICE_ID,true);
//			}
//			if(disTime<16){
//				if(result_code.equals("00")){
//					logger.info(DEVICE_ID+"设备gprs发卡回调ok========================0");
//					daHaoLockUtil.sendTenCard(DEVICE_ID, false);//发卡ok
//				}else{
//					daHaoLockUtil.sendTenCard(DEVICE_ID, true);//发卡ok
//				}
//			}
        }
        if (OPERATE.equals("AB")) { // 批量导入卡片回调
            logger.info("框架内导入卡片回调========================");
            logger.info(resultJson.toString());
            int result = resultJson.getInt("RESULT");
            if (result == 0) {
                String DEVICE_ID = resultJson.getString("DEVICEID");//设备Id
                JSONArray sixteenCardArr = resultJson.getJSONArray("PARAMS");
//				{"DEVICEID":"F369FB8C","RESULT":0,"OPERATE":"AB","PARAMS":["F369FB8C","00","00000001",,"00000002",,"00000003",,"00000004"]
                if (sixteenCardArr != null && sixteenCardArr.size() > 2) {
                    StringBuilder cardNumStr = null;
                    EstateDoorCard idDoorCard  = null;
                    Long lockCardIdStart = null;
                    for (int x = 1; x < sixteenCardArr.size(); x++) {
//                        sixteenCards.add(sixteenCardArr.get(x).toString());
                        if(cardNumStr == null){
                            idDoorCard = new EstateDoorCard();
                            lockCardIdStart = idDoorCard.returnIdLong();
                            cardNumStr= new StringBuilder().append("'").append(sixteenCardArr.get(x).toString());
                        }
                        if(cardNumStr != null){
                            idDoorCard.returnIdLong();// id自增 避免重复
                            cardNumStr.append(",").append(sixteenCardArr.get(x).toString());
                        }
                    }
                    if(cardNumStr!=null){
                        cardNumStr.append("'");
                        daHaoLockUtil.saveSendCardRecordByFunction(DEVICE_ID,cardNumStr.toString(),lockCardIdStart);
                    }
//                    daHaoLockUtil.sendCardCallBackOkToAddRecord(DEVICE_ID, sixteenCards);
                }
            }
        }
        if (OPERATE.equals("AC")) {
            logger.info("框架内导入卡片完成========================");
            logger.info(resultJson.toString());
//			String DEVICE_ID = resultJson.getString("DEVICEID");//设备Id
//			daHaoLockUtil.sendCardCallBackOkToAddRecord(DEVICE_ID);
        }
        if (OPERATE.equals("28")) {//删除卡片
            String PARAMS_str = resultJson.getString("PARAMS");
            JSONArray PARAMS_Array = JSONArray.fromObject(PARAMS_str);
            String DEVICE_ID = PARAMS_Array.get(0).toString();//设备Id
            String result_code = PARAMS_Array.get(1).toString();
            if (result_code.equals("00")) {
                logger.info(DEVICE_ID + "设备gprs删卡成功========================0");
            } else {
                logger.info(DEVICE_ID + "设备gprs删卡失败========================1");
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg", "ok");
        map.put("result", 0);
        map.put("data", resultJson);
        return map;
    }

}
